package com.stox.client.api.core;

import java.util.Collection;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

@Component
@Lazy(false)
public class ClientFactory implements InitializingBean{

	private static Collection<? extends Client> clients;
	
	@Autowired
	private ApplicationContext applicationContext;
	
	@Override
	public void afterPropertiesSet() throws Exception {
		clients = applicationContext.getBeansOfType(Client.class).values();
	}
	
	@SuppressWarnings("unchecked")
	public static <T extends Client> T getClient(Class<T> clientClass){
		for(Client client : clients){
			if(clientClass.isAssignableFrom(client.getClass())){
				return (T) client;
			}
		}
		return null;
	}
	
}
